package com.wjjm.spoonselling.controller;

import com.wjjm.spoonselling.pojo.Merchant;
import com.wjjm.spoonselling.service.MerchantService;
import com.wjjm.spoonselling.util.CheckCodeUtil;
import com.wjjm.spoonselling.util.Code;
import com.wjjm.spoonselling.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/merchant")
public class MerchantController {

    @Autowired
    private MerchantService merchantService;

    @PostMapping("/login")
    public Result login(@RequestBody Merchant merchant, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

        //获取验证码
        String checkCode = merchant.getCheckCode();
        //判断验证码
        //获取程序生成的验证码
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");

        //忽略大小写equalsIgnoreCase
        if (!checkCodeGen.equalsIgnoreCase(checkCode)){
            return Result.fail("验证码错误");
        }

        return merchantService.login(merchant);
    }

    @PostMapping("/register")
    public Result register(@RequestBody Merchant merchant){
        return merchantService.register(merchant);
    }

    @GetMapping("/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

        //生成验证码
        ServletOutputStream os = response.getOutputStream();
        //输出随机验证码图片流,并返回验证码值
        String checkcode = CheckCodeUtil.outputVerifyImage(100,50,os,4);
        //存入session.setAttribute(名称,要保存的对象)
        session.setAttribute("checkCodeGen",checkcode);

    }

    @GetMapping("/selectByName/{name}")
    public Result selectByName(@PathVariable String name){
        Merchant merchant = merchantService.selectByName(name);
        int code = merchant != null ? Code.SELECT_OK:Code.SELECT_ERR;
        String msg = merchant != null ? "数据查询成功":"数据查询失败，请重试";
        return new Result(code,merchant,msg);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Merchant merchant){
        boolean flag = merchantService.update(merchant);
        int code = flag == true ? Code.UPDATE_OK:Code.UPDATE_ERR;
        String msg = flag == true ? "数据更新成功":"数据更新失败，请重试";
        return new Result(code,flag,msg);
    }
}
